<?php

namespace app\saas\model;

use app\common\model\trAdmin;
use app\common\util\ErrorCode;
use app\common\util\Tools;
use think\Model;

/**
 * Class Auth
 * @package app\saas\model
 * 商城表
 */
class trMall extends Model
{
    protected $pk = 'id';
    protected $resultSetType = 'collection'; //申明结果集是数据集对象（collection），查询结果才能用toArray()方法转为数组
    protected $name = "mall"; //表名

    protected $type = [
        'create_time'  =>  'timestamp:Y-m-d H:i',
        'update_time'  =>  'timestamp:Y-m-d H:i',
    ];

    public static function transferField($data){
        if(!$data){
            return [];
        }
        $data = Tools::transferFields($data);
        if(isset($data[0])){
            foreach ($data as $k => $item){
                if(isset($item["managerId"])){
                    if(empty($adminData[$item["managerId"]])){
                        $adminData[$item["managerId"]] = trAdmin::where("id", $item["managerId"])->field("username,mobile")->find();
                    }
                    $data[$k]["managerName"] = isset($adminData[$item["managerId"]]["username"]) ? $adminData[$item["managerId"]]["username"] : "";
                    $data[$k]["managerMobile"] = isset($adminData[$item["managerId"]]["mobile"]) ? $adminData[$item["managerId"]]["mobile"] : "";
                }
            }
        }else{
            if(isset($data["managerId"])){
                if(empty($adminData[$data["managerId"]])){
                    $adminData[$data["managerId"]] = trAdmin::where("id", $data["managerId"])->field("username,mobile")->find();
                }
                $data["managerName"] = isset($adminData[$data["managerId"]]["username"]) ? $adminData[$data["managerId"]]["username"] : "";
                $data["managerMobile"] = isset($adminData[$data["managerId"]]["mobile"]) ? $adminData[$data["managerId"]]["mobile"] : "";
            }
        }
        return $data;
    }

    //分页获取所有字段数据
    public static function getList($field = '*', $filter = [], $page = 1, $limit = 10, $order = "create_time desc", $paginate = true){
        $db = self::where($filter)->field($field)->order($order);
        if($paginate){
            $data = $db->paginate(array('page' => $page, 'list_rows' => $limit));
            if($data){
                $data = $data->toArray();
                $data["data"] = self::transferField($data["data"]);
                return $data;
            }
        }else{
            if($page && $limit)
                $db->limit($page-1, $limit);
            $data = $db->select();
            $data = self::transferField($data->toArray());
            return $data;
        }
        return [];
    }

    //根据条件获取数量
    public static function getCount($filter){
        if(!empty($filter)){
            return self::where($filter)->count();
        }else{
            return self::count();
        }
    }

    //添加
    public static function toAdd($data, $getId=false){
        if(!$data)
            return true;
        try {
            if(empty($data["create_time"])) $data["create_time"] = time();
            $model = self::create($data);
            if ($getId) {
                return $model->id;
            } else {
                return $model;
            }
        }catch (\Exception $e){
            return ErrorCode::code("try_error", $e->getMessage());
        }
    }

    //更新
    public static function doUpdate($data, $filter = []){
        if(!$data)
            return true;
        if(!isset($filter["id"])){
            $filter["id"] = self::where($filter)->value("id");
        }
        if(!empty($data["name"])){
            if(self::getCount([["name", '=', $data["name"]], ["id", '<>', $filter["id"]]])){
                return ErrorCode::code("customized", "商城名称已存在");
            }
        }
        if(empty($data["update_time"])) $data["update_time"] = time();
        if(self::update($data, $filter)){
            if($mallData = cache("systemMallData_{$filter["id"]}")){
                cache("systemMallData_{$filter["id"]}", array_merge($mallData, Tools::transferFields($data)));
            }
            return true;
        }else{
            return false;
        }
    }

    //获取多字段数据
    public static function getFields($field, $filter = [], $one = true, $toArray = true){ //缓存方法：缓存所有字段，只返回需要的字段
        if($one){
            $data = self::where($filter)->field($field)->find();
            return $data ? ($toArray ? self::transferField($data->toArray()) : Tools::transferFields($data->getData())) : [];
        }else{
            $data = self::where($filter)->field($field)->select();
            return $data ? ($toArray ? self::transferField($data->toArray()) : $data) : [];
        }
    }

    //根据ID删除数据
    public static function delById($id){
        if(is_array($id)){
            $result = self::where('id', 'in', $id)->delete();
        }else{
            $result = self::where('id', $id)->delete();
            $id = [$id];
        }
        if($result){
            foreach ($id as $i){
                cache("systemMallData_{$i}", null);
            }
        }
        return $result;
    }

    public static function getCacheData($mallId){
        if(!$mallData = cache("systemMallData_{$mallId}")){
            if(empty($mallData = self::getFields("*", ["id" => $mallId], true, false))) {
                return false;
            }
            cache("systemMallData_{$mallId}", $mallData);
        }
        return $mallData;
    }
}